package com.wcgksoft.source;

import com.wcgksoft.common.util.getdata.AnalysisCallBack;
import com.wcgksoft.common.util.getdata.AnalysisHelper;
import com.wcgksoft.common.util.getdata.JXCTPacket;
import com.wcgksoft.common.util.getdata.Log;
import com.wcgksoft.entity.ZData.BasicData;
import com.wcgksoft.service.BasicDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.List;

public class TcpServer extends Thread {
    private static BasicDataService basicDataService;
    @Autowired
    public void setDatastore(BasicDataService basicDataService) {
        TcpServer.basicDataService = basicDataService;
    }
    Socket clientSocket;


    public TcpServer(Socket clientSocket) {
        this.clientSocket = clientSocket;
    }

    public TcpServer() {

    }

    /**
     * 启动 Tcp Server
     *
     */
    public  void startServer() {
        new Thread() {
            @Override
            public void run() {
                try {
                    //建立TCP连接服务,绑定端口
                    ServerSocket tcpServer = new ServerSocket(19999);
                    Log.print("端口19999启动成功");
                    while (true) {
                        new TcpServer(tcpServer.accept()).start();
                    }
                } catch (Exception e) {

                    Log.print(e.toString());
                    e.printStackTrace();
                }
            }
        }.start();

    }

    @Override
    public void run() {
        try {
            //获得客户端的ip地址和主机名
            final String name = clientSocket.getInetAddress().getHostName() + "(" + clientSocket.getInetAddress().getHostAddress() + ")";
            Log.print(name + " 连接成功!");
            //获取客户端的OutputStream
            InputStream in = clientSocket.getInputStream();
            final byte b[] = new byte[512];     //创建合适文件大小的数组
            while (true) {
                int len = in.read(b);//读取数据
                if (len > 0) {
                    byte[] datas = new byte[len];
                    System.arraycopy(b, 0, datas, 0, len);
                    analysis(name, datas);//解析数据
                    clientSocket.getOutputStream().write(new byte[]{00});//回复设备ack 正确00 失败EE
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param name  名称
     * @param datas 数据
     */
    protected void analysis(final String name, byte[] datas) {
        AnalysisHelper.solution(datas, new AnalysisCallBack() {
            public void onSuccess(JXCTPacket packet) {
                Log.print(name + " -> " + packet);
                List<String> body = packet.getBody();
                for (int i = 0; i < body.size() / 4; i++) {
                    BasicData data1 = new BasicData();
                    data1.setAcquisitiontime(new Date());
                    data1.setNo(packet.getDeviceNumber());
                    String hex = AnalysisHelper.getParseVal(body, i * 4, 4);
                    double val = AnalysisHelper.getAnalysisVal(hex);
                    java.text.DecimalFormat df =new java.text.DecimalFormat("#.0");

                    switch (i){
                        case 0:
                            System.out.println("温度");
                            data1.setCom("通道"+i);
                            data1.setData(String.valueOf(df.format(val*0.1)));
                            data1.setHmdata(String.valueOf(df.format(val*0.1)));
                            data1.setDatatype("wd");
                            basicDataService.save(data1);
                            break;
                        case 1:
                            System.out.println("湿度");
                            data1.setCom("通道"+i);
                            data1.setData(String.valueOf(df.format(val*0.1)));
                            data1.setHmdata(String.valueOf(df.format(val*0.1)));
                            data1.setDatatype("sd");
                            basicDataService.save(data1);
                            break;
                        case 2:
                            System.out.println("光照");
                            data1.setCom("通道"+i);
                            data1.setData(String.valueOf(val));
                            data1.setHmdata(String.valueOf(val));
                            data1.setDatatype("gzqd");
                            basicDataService.save(data1);
                            break;
                        case 3:
                            System.out.println("二氧化碳");
                            data1.setCom("通道"+i);
                            data1.setData(String.valueOf(val));
                            data1.setHmdata(String.valueOf(val));
                            data1.setDatatype("co2");
                            basicDataService.save(data1);
                            break;
                        case 4:
                            System.out.println("氨气");
                            data1.setCom("通道"+i);
                            data1.setData(String.valueOf(val*0.01));
                            data1.setHmdata(String.valueOf(val*0.01));
                            data1.setDatatype("aq");
                            basicDataService.save(data1);
                            break;
                        case 5:
                            System.out.println("信号强度");
                            data1.setCom("通道"+i);
                            data1.setData(String.valueOf(val));
                            data1.setHmdata(String.valueOf(val));
                            data1.setDatatype("signal");
                            basicDataService.save(data1);
                            break;
                        case 6:
                            System.out.println("错误码"+val);
                            break;
                        case 7:
                            System.out.println("版本号"+val*0.1);
                            break;
                        default:
                            System.out.println("数据解析出现问题");
                    }
                    //Log.print((i + 1) + " : " + hex + "  -> " + val);
                }
            }

            public void onFailure(String msg) {
                Log.print(name + " -> " + msg);
            }
        });
    }
}